package com.lagou.task.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBUtil {
    private static String jdbcName; // 描述驱动信息
    private static String dbUrl; // 描述url信息
    private static String dbUsername;
    private static String dbPassword;
    // 进行静态成员初始化操作
    static {
        jdbcName = "com.mysql.cj.jdbc.Driver";
        dbUrl = "jdbc:mysql://localhost:3306/db_web?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
        dbUsername = "root";
        dbPassword = "root";
        try {
            Class.forName(jdbcName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection con = DriverManager.getConnection(dbUrl,dbUsername,dbPassword);
        return con;
    }

    /**
     * 关闭连接
     * @param con
     * @throws SQLException
     */
    public static void closeSource(Connection con, PreparedStatement preparedStatement) throws SQLException {
        if(null!=con){
            con.close();
        }
        if(null!=preparedStatement){
            preparedStatement.close();
        }
    }
}
